package org.linphone.http;

import android.app.Service;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;
//import com.yanzhenjie.andserver.website.AssetsWebsite;

import java.util.concurrent.TimeUnit;

/**
 * Created by Xiang on 2017/12/4.
 */

public class HtmlService extends Service {
	private static final String TAG = "AndServerService";
	/**
	 * AndServer.
	 */
	//private Server mServer;

	private AssetManager mAssetManager;
	private Server mAndserver;
	@Override
	public void onCreate() {
		mAssetManager = getAssets();
		mAndserver = AndServer.serverBuilder(this)
				.inetAddress(NewIPUtil.getInetAddress(this))
                //   .inetAddress(IpUtils.getInetAddress(this))
				.port(8089)
				.timeout(20*1000, TimeUnit.MILLISECONDS)
				.listener(new Server.ServerListener() {
					@Override
					public void onStarted() {
						LogUtil.i(TAG,"AndServer启动");
					}
					@Override
					public void onStopped() {
						LogUtil.i(TAG,"AndServer关闭");
						mAndserver.startup();
					}

					@Override
					public void onException(Exception e) {
						LogUtil.i(TAG,"服务启动异常"+e.getMessage());
					}
				})
				.build();


		//mServer = andServer.createServer();

	}


	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		startServer();
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		stopServer(); // Stop server.

		if (mAssetManager != null)
			mAssetManager.close();
	}

	/**
	 * Start server.
	 */
	private void startServer() {
		if(!mAndserver.isRunning()){
			//启动AndServer
			mAndserver.startup();
		}

	}

	/**
	 * Stop server.
	 */
	private void stopServer() {
		if (mAndserver != null) {
			mAndserver.shutdown();
			Toast.makeText(this,"AndServer服务关闭了",Toast.LENGTH_SHORT).show();
		}

	}

	@Nullable
	@Override
	public IBinder onBind(Intent intent) {
		return null;

	}

}
